<template>
  <div class="upload-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文件上传</span>
        </div>
      </template>
      
      <div class="upload-area">
        <el-upload
          ref="uploadRef"
          class="upload-dragger"
          drag
          multiple
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          accept="video/*,audio/*"
        >
          <el-icon class="el-icon--upload" size="67"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持视频和音频文件，单个文件大小不超过 500MB
            </div>
          </template>
        </el-upload>
      </div>
    </el-card>

    <!-- 上传队列 -->
    <el-card v-if="uploadTasks.length > 0" style="margin-top: 24px;">
      <template #header>
        <div class="card-header">
          <span>上传队列 ({{ uploadTasks.length }})</span>
          <div>
            <el-button
              type="primary"
              :disabled="!hasWaitingTasks || isUploading"
              @click="startUpload"
            >
              {{ isUploading ? '上传中...' : '开始上传' }}
            </el-button>
            <el-button @click="clearCompleted">清除已完成</el-button>
            <el-button type="danger" @click="clearAll">清空队列</el-button>
          </div>
        </div>
      </template>

      <div class="upload-queue">
        <div
          v-for="task in uploadTasks"
          :key="task.id"
          class="upload-task"
        >
          <div class="task-info">
            <div class="task-icon">
              <el-icon size="24">
                <VideoCamera v-if="task.file.type.startsWith('video/')" />
                <Headphone v-else />
              </el-icon>
            </div>
            <div class="task-details">
              <div class="task-name">{{ task.name }}</div>
              <div class="task-meta">
                {{ formatFileSize(task.file.size) }} · 
                {{ task.file.type }}
              </div>
            </div>
          </div>

          <div class="task-progress">
            <el-progress
              :percentage="task.progress"
              :status="getProgressStatus(task.status)"
              :stroke-width="8"
            />
            <div class="task-status">
              {{ getStatusText(task.status) }}
              <span v-if="task.error" class="error-text">: {{ task.error }}</span>
            </div>
          </div>

          <div class="task-actions">
            <el-button
              v-if="task.status === 'waiting'"
              size="small"
              type="danger"
              @click="removeTask(task.id)"
            >
              移除
            </el-button>
            <el-button
              v-else-if="task.status === 'error'"
              size="small"
              type="primary"
              @click="retryTask(task)"
            >
              重试
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 上传历史 -->
    <el-card style="margin-top: 24px;">
      <template #header>
        <span>最近上传</span>
      </template>
      
      <el-table :data="recentUploads" style="width: 100%">
        <el-table-column prop="name" label="文件名" min-width="200" />
        <el-table-column prop="size" label="大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'completed' ? 'success' : 'danger'">
              {{ row.status === 'completed' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadTask } from '@/types'

const uploadRef = ref()
const uploadTasks = ref<UploadTask[]>([])
const isUploading = ref(false)

// 模拟最近上传记录
const recentUploads = ref([
  {
    name: '示例视频.mp4',
    size: 1024 * 1024 * 50,
    uploadTime: '2024-01-15 10:30:00',
    status: 'completed'
  },
  {
    name: '音乐文件.mp3',
    size: 1024 * 1024 * 8,
    uploadTime: '2024-01-14 15:20:00',
    status: 'completed'
  }
])

const hasWaitingTasks = computed(() => {
  return uploadTasks.value.some(task => task.status === 'waiting')
})

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    waiting: '等待上传',
    uploading: '上传中',
    processing: '处理中',
    completed: '已完成',
    error: '上传失败'
  }
  return statusMap[status] || status
}

// 获取进度条状态
const getProgressStatus = (status: string) => {
  if (status === 'error') return 'exception'
  if (status === 'completed') return 'success'
  return undefined
}

// 文件选择
const handleFileChange = (file: any) => {
  // 检查文件大小
  if (file.size > 500 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 500MB')
    return false
  }

  // 检查文件类型
  const isValidType = file.type.startsWith('video/') || file.type.startsWith('audio/')
  if (!isValidType) {
    ElMessage.error('只支持视频和音频文件')
    return false
  }

  const task: UploadTask = {
    id: Date.now().toString() + Math.random(),
    file: file.raw,
    name: file.name,
    progress: 0,
    status: 'waiting'
  }

  uploadTasks.value.push(task)
}

// 移除文件
const handleFileRemove = (file: any) => {
  const index = uploadTasks.value.findIndex(task => task.file === file.raw)
  if (index > -1) {
    uploadTasks.value.splice(index, 1)
  }
}

// 移除任务
const removeTask = (id: string) => {
  const index = uploadTasks.value.findIndex(task => task.id === id)
  if (index > -1) {
    uploadTasks.value.splice(index, 1)
  }
}

// 重试任务
const retryTask = (task: UploadTask) => {
  task.status = 'waiting'
  task.progress = 0
  task.error = undefined
}

// 模拟上传进度
const simulateUpload = (task: UploadTask): Promise<void> => {
  return new Promise((resolve, reject) => {
    task.status = 'uploading'
    
    const interval = setInterval(() => {
      task.progress += Math.random() * 15 + 5
      
      if (task.progress >= 100) {
        task.progress = 100
        task.status = 'processing'
        clearInterval(interval)
        
        // 模拟处理时间
        setTimeout(() => {
          if (Math.random() > 0.1) { // 90% 成功率
            task.status = 'completed'
            resolve()
          } else {
            task.status = 'error'
            task.error = '上传失败'
            reject(new Error('上传失败'))
          }
        }, 1500)
      }
    }, 300)
  })
}

// 开始上传
const startUpload = async () => {
  const waitingTasks = uploadTasks.value.filter(task => task.status === 'waiting')
  if (waitingTasks.length === 0) return
  
  isUploading.value = true
  
  try {
    // 并发上传
    const promises = waitingTasks.map(task => simulateUpload(task))
    await Promise.allSettled(promises)
    
    const completedCount = uploadTasks.value.filter(task => task.status === 'completed').length
    const errorCount = uploadTasks.value.filter(task => task.status === 'error').length
    
    if (completedCount > 0) {
      ElMessage.success(`成功上传 ${completedCount} 个文件`)
    }
    
    if (errorCount > 0) {
      ElMessage.warning(`${errorCount} 个文件上传失败`)
    }
    
  } catch (error) {
    ElMessage.error('上传过程中发生错误')
  } finally {
    isUploading.value = false
  }
}

// 清除已完成
const clearCompleted = () => {
  uploadTasks.value = uploadTasks.value.filter(task => 
    task.status !== 'completed' && task.status !== 'error'
  )
}

// 清空队列
const clearAll = () => {
  uploadTasks.value = []
  uploadRef.value?.clearFiles()
}
</script>

<style scoped>
.upload-page {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-area {
  padding: 20px 0;
}

.upload-queue {
  max-height: 400px;
  overflow-y: auto;
}

.upload-task {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 12px;
  background: #fafafa;
}

.task-info {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 20px;
}

.task-icon {
  margin-right: 12px;
  color: #666;
}

.task-details {
  flex: 1;
}

.task-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.task-meta {
  font-size: 12px;
  color: #666;
}

.task-progress {
  flex: 2;
  margin-right: 20px;
}

.task-status {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.error-text {
  color: #f56c6c;
}

.task-actions {
  flex: 0 0 auto;
}
</style> 